<template>
  <div>
    <el-card>
      <div style="margin-bottom: 16px;">
        <el-button type="primary" @click="openForm()">新增SKU</el-button>
        <el-upload
          :show-file-list="false"
          :before-upload="handleImport"
          accept=".xlsx,.csv"
        >
          <el-button>导入</el-button>
        </el-upload>
        <el-button @click="handleExport('xlsx')">导出Excel</el-button>
        <el-button @click="handleExport('csv')">导出CSV</el-button>
        <el-button type="success" @click="openImportFromItemsDialog">从商品管理导入</el-button>
        <el-button type="primary" @click="handleAIClean">AI清洗</el-button>
        <el-button type="warning" @click="handleUpdateBaseNum">更新基础数量</el-button>
        
        <!-- 筛选按钮组 -->
        <el-button-group style="margin-left: 16px;">
          <el-button 
            :type="handledFilter === null ? 'primary' : ''"
            @click="setHandledFilter(null)"
          >
            <el-icon><Filter /></el-icon>
            全部记录 ({{ total }})
          </el-button>
          <el-button 
            :type="handledFilter === false ? 'warning' : ''"
            @click="setHandledFilter(false)"
          >
            <el-icon><Flag /></el-icon>
            未标记记录
          </el-button>
          <el-button 
            :type="handledFilter === true ? 'success' : ''"
            @click="setHandledFilter(true)"
          >
            <el-icon><Flag /></el-icon>
            已标记记录
          </el-button>
        </el-button-group>
        
        <el-input v-model="search" placeholder="搜索商品名" style="width: 200px; margin-left: 16px;" @keyup.enter="fetchList"/>
      </div>
      <el-table :data="list" border @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column label="标记" width="60" align="center">
          <template #default="{ row }">
            <el-icon 
              :class="{ 'human_tag': row.human_tag }"
              @click="toggleHandleStatus(row)"
              style="cursor: pointer; font-size: 20px;"
            >
              <Flag />
            </el-icon>
          </template>
        </el-table-column>
        <el-table-column prop="id" label="ID" width="60"/>
        <el-table-column prop="item_name" label="商品名"/>
        <el-table-column prop="item_img" label="商品图片" width="100">
          <template #default="scope">
            <el-image 
              v-if="scope.row.item_img"
              :src="scope.row.item_img" 
              :preview-src-list="[scope.row.item_img]"
              :initial-index="0"
              :preview-teleported="true"
              :zoom-rate="1.2"
              :preview-options="{
                zoom: 1,
                closeOnPressEscape: true,
                maskClosable: true
              }"
              fit="contain"
              style="width: 50px; height: 50px; cursor: pointer;"
            >
              <template #error>
                <div class="image-slot">
                  <el-icon><picture-filled /></el-icon>
                </div>
              </template>
            </el-image>
            <span v-else>暂无图片</span>
          </template>
        </el-table-column>
        <el-table-column prop="cleaned_name" label="清洗后名称">
          <template #default="scope">
            <el-input v-if="editingCell.rowId === scope.row.id && editingCell.field === 'cleaned_name'" v-model="editCache.cleaned_name" size="small" :style="{ height: '32px' }" @blur="handleSaveCell(scope.row, 'cleaned_name')" @keyup.enter="handleSaveCell(scope.row, 'cleaned_name')" />
            <span v-else @click="openEditCell(scope.row, 'cleaned_name')" style="min-width: 60px; display: inline-block; cursor: pointer; color: #999;">{{ scope.row.cleaned_name || '点击编辑' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="item_brand" label="品牌">
          <template #default="scope">
            <el-input v-if="editingCell.rowId === scope.row.id && editingCell.field === 'item_brand'" v-model="editCache.item_brand" size="small" :style="{ height: '32px' }" @blur="handleSaveCell(scope.row, 'item_brand')" @keyup.enter="handleSaveCell(scope.row, 'item_brand')" />
            <span v-else @click="openEditCell(scope.row, 'item_brand')" style="min-width: 60px; display: inline-block; cursor: pointer; color: #999;">{{ scope.row.item_brand || '点击编辑' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="item_specs" label="规格">
          <template #default="scope">
            <el-input v-if="editingCell.rowId === scope.row.id && editingCell.field === 'item_specs'" v-model="editCache.item_specs" size="small" :style="{ height: '32px' }" @blur="handleSaveCell(scope.row, 'item_specs')" @keyup.enter="handleSaveCell(scope.row, 'item_specs')" />
            <span v-else @click="openEditCell(scope.row, 'item_specs')" style="min-width: 60px; display: inline-block; cursor: pointer; color: #999;">{{ scope.row.item_specs || '点击编辑' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="item_price" label="价格"/>
        <el-table-column prop="item_classification" label="分类"/>
        <el-table-column prop="base_price" label="基础价格">
          <template #default="scope">
            <el-input-number v-if="editingCell.rowId === scope.row.id && editingCell.field === 'base_price'" v-model="editCache.base_price" size="small" :min="0" :step="0.01" :style="{ height: '32px' }" @blur="handleSaveCell(scope.row, 'base_price')" @keyup.enter="handleSaveCell(scope.row, 'base_price')" />
            <span v-else @click="openEditCell(scope.row, 'base_price')" style="min-width: 60px; display: inline-block; cursor: pointer; color: #999;">{{ scope.row.base_price || '点击编辑' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="base_unit" label="基础单位">
          <template #default="scope">
            <el-input v-if="editingCell.rowId === scope.row.id && editingCell.field === 'base_unit'" v-model="editCache.base_unit" size="small" :style="{ height: '32px' }" @blur="handleSaveCell(scope.row, 'base_unit')" @keyup.enter="handleSaveCell(scope.row, 'base_unit')" />
            <span v-else @click="openEditCell(scope.row, 'base_unit')" style="min-width: 60px; display: inline-block; cursor: pointer; color: #999;">{{ scope.row.base_unit || '点击编辑' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="base_num" label="基础数量">
          <template #default="scope">
            <el-input-number v-if="editingCell.rowId === scope.row.id && editingCell.field === 'base_num'" v-model="editCache.base_num" size="small" :min="0" :step="1" :style="{ height: '32px' }" @blur="handleSaveCell(scope.row, 'base_num')" @keyup.enter="handleSaveCell(scope.row, 'base_num')" />
            <span v-else @click="openEditCell(scope.row, 'base_num')" style="min-width: 60px; display: inline-block; cursor: pointer; color: #999;">{{ scope.row.base_num || '点击编辑' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="package_type" label="包装类型">
          <template #default="scope">
            <el-input v-if="editingCell.rowId === scope.row.id && editingCell.field === 'package_type'" v-model="editCache.package_type" size="small" :style="{ height: '32px' }" @blur="handleSaveCell(scope.row, 'package_type')" @keyup.enter="handleSaveCell(scope.row, 'package_type')" />
            <span v-else @click="openEditCell(scope.row, 'package_type')" style="min-width: 60px; display: inline-block; cursor: pointer; color: #999;">{{ scope.row.package_type || '点击编辑' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="sku" label="SKU编码"/>
        <el-table-column prop="created_at" label="创建时间"/>
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button size="small" @click="openForm(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete([scope.row.id])">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="page"
        v-model:page-size="pageSize"
        :total="total"
        @current-change="fetchList"
        @size-change="fetchList"
        layout="total, prev, pager, next, sizes"
        :page-sizes="[10, 20, 50, 100]"
        style="margin-top: 16px;"
      />
    </el-card>
    <SkuForm v-if="showForm" :sku="currentSku" @close="closeForm" @refresh="fetchList"/>

    <!-- 从商品管理导入对话框 -->
    <el-dialog
      title="从商品管理导入"
      v-model="importFromItemsDialogVisible"
      width="500px"
    >
      <el-form :model="importForm" label-width="120px">
        <el-form-item label="每批处理数量">
          <el-input-number v-model="importForm.batchSize" :min="10" :max="1000" :step="10"></el-input-number>
        </el-form-item>
        <el-form-item label="超市ID">
          <el-input v-model="importForm.shopId" placeholder="可选，按超市ID筛选"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="importFromItemsDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleImportFromItems" :loading="importing">开始导入</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 数据清洗确认对话框 -->
    <el-dialog
      title="数据清洗"
      v-model="cleanDialogVisible"
      width="500px"
    >
      <p>数据清洗将分析商品名称，提取品牌、规格信息，并计算基础单价。</p>
      <p>您可以选择清洗：</p>
      <el-radio-group v-model="cleanMode">
        <el-radio :label="'selected'" v-if="selectedRows.length > 0">仅清洗选中的 {{ selectedRows.length }} 条记录</el-radio>
        <el-radio :label="'all'">清洗所有记录</el-radio>
      </el-radio-group>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cleanDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmCleanData" :loading="cleaning">开始清洗</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- AI清洗确认对话框 -->
    <el-dialog
      title="AI智能清洗"
      v-model="aiCleanDialogVisible"
      width="500px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="!aiCleaning"
    >
      <template #default>
        <div v-if="!aiCleanProgress">
          <p>AI智能清洗将使用深度学习模型分析商品名称，提取以下信息：</p>
          <ul>
            <li>商品品牌</li>
            <li>规格信息</li>
            <li>包装类型</li>
            <li>基础单位</li>
            <li>清洗后的标准名称</li>
          </ul>
          <p>您可以选择清洗：</p>
          <el-radio-group v-model="aiCleanMode">
            <el-radio :label="'selected'" v-if="selectedRows.length > 0">仅清洗选中的 {{ selectedRows.length }} 条记录</el-radio>
            <el-radio :label="'all'">清洗所有记录</el-radio>
          </el-radio-group>
          
          <div style="margin-top: 15px;">
            <el-checkbox v-model="skipHandled">跳过已标记的记录（推荐）</el-checkbox>
            <p style="font-size: 12px; color: #888; margin-top: 5px;">
              启用此选项时，将跳过已经处理过的记录，避免重复处理
            </p>
          </div>
        </div>
        <div v-else>
          <el-progress 
            :percentage="Math.round((aiCleanProgress.processed_count / aiCleanProgress.total_count) * 100)"
            :status="aiCleanProgress.status === 'error' ? 'exception' : aiCleanProgress.status === 'completed' ? 'success' : ''"
          />
        </div>
      </template>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="aiCleanDialogVisible = false" :disabled="aiCleaning">取消</el-button>
          <el-button type="primary" @click="confirmAIClean" :loading="aiCleaning" :disabled="aiCleaning">
            {{ aiCleaning ? '处理中...' : '开始清洗' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { PictureFilled, Flag, Filter } from '@element-plus/icons-vue'
import SkuForm from './SkuForm.vue'
import axios from 'axios'

const list = ref([])
const total = ref(0)
const page = ref(1)
const pageSize = ref(20)
const search = ref('')
const handledFilter = ref(null)  // 筛选状态：null=全部, false=未标记, true=已标记
const showForm = ref(false)
const currentSku = ref(null)
const selectedRows = ref([])

// 从商品管理导入相关变量
const importFromItemsDialogVisible = ref(false)
const importForm = ref({
  batchSize: 100,
  shopId: ''
})
const importing = ref(false)

// 清洗相关变量
const cleanDialogVisible = ref(false)
const cleanMode = ref('all')
const cleaning = ref(false)

// AI清洗相关变量
const aiCleanDialogVisible = ref(false)
const aiCleanMode = ref('all')
const skipHandled = ref(true)  // 默认跳过已处理记录
const aiCleaning = ref(false)
const aiCleanTaskId = ref('')
const aiCleanProgress = ref(null)
const aiCleanTimer = ref(null)

// 更新基础数量相关变量
const updateBaseNumLoading = ref(false)
const updateBaseNumProgress = ref(null)
const updateBaseNumTimer = ref(null)

const editingCell = ref({ rowId: null, field: '' })
const editCache = ref({})

function fetchList() {
  const params = { 
    page: page.value, 
    page_size: pageSize.value, 
    search: search.value 
  }
  
  // 添加处理状态筛选参数
  if (handledFilter.value !== null) {
    params.human_tag = handledFilter.value
  }
  
  axios.get('/api/sku/list', { params }).then(res => {
    list.value = res.data.items
    total.value = res.data.total
  }).catch(error => {
    ElMessage.error(`获取SKU列表失败: ${error.message}`)
  })
}

function openForm(sku = null) {
  currentSku.value = sku
  showForm.value = true
}
function closeForm() {
  showForm.value = false
  currentSku.value = null
}

function handleSelectionChange(rows) {
  selectedRows.value = rows
}

function handleDelete(ids) {
  ElMessageBox.confirm('确定要删除选中的SKU吗？', '提示', { type: 'warning' })
    .then(() => {
      axios.post('/api/sku/delete', { ids }).then(() => {
        ElMessage.success('删除成功')
        fetchList()
      }).catch(error => {
        ElMessage.error(`删除失败: ${error.response?.data?.detail || error.message}`)
      })
    })
}

function handleImport(file) {
  const formData = new FormData()
  formData.append('file', file)
  axios.post('/api/sku/import', formData).then(res => {
    ElMessage.success(`导入成功，共${res.data.count}条`)
    fetchList()
  }).catch(error => {
    ElMessage.error(`导入失败: ${error.response?.data?.detail || error.message}`)
  })
  return false
}

function handleExport(format) {
  axios.get(`/api/sku/export?format=${format}`, { responseType: 'blob' })
    .then(res => {
      const url = window.URL.createObjectURL(new Blob([res.data]))
      const link = document.createElement('a')
      link.href = url
      link.setAttribute('download', `sku.${format}`)
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    })
    .catch(error => {
      ElMessage.error(`导出失败: ${error.message}`)
    })
}

// 打开从商品管理导入对话框
function openImportFromItemsDialog() {
  importFromItemsDialogVisible.value = true
}

// 处理从商品管理导入
function handleImportFromItems() {
  importing.value = true
  
  // 构建请求参数
  const params = {
    batch_size: importForm.value.batchSize
  }
  
  // 如果有超市ID，添加到参数中，确保转换为有效整数
  if (importForm.value.shopId && !isNaN(parseInt(importForm.value.shopId))) {
    params.shop_id = parseInt(importForm.value.shopId)
  }
  
  // 显示加载中
  const loadingInstance = ElLoading.service({
    lock: true,
    text: '正在导入数据，请稍候...',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  
  // 发送请求
  axios.get('/api/sku/import-from-items', { params })
    .then(res => {
      ElMessage.success(res.data.message)
      importFromItemsDialogVisible.value = false
      fetchList()
    })
    .catch(error => {
      ElMessage.error(`导入失败: ${error.response?.data?.detail || error.message}`)
      console.error('导入错误详情:', error)
    })
    .finally(() => {
      importing.value = false
      loadingInstance.close()
    })
}

// 打开数据清洗对话框
function handleCleanData() {
  cleanMode.value = selectedRows.value.length > 0 ? 'selected' : 'all'
  cleanDialogVisible.value = true
}

// 确认数据清洗
function confirmCleanData() {
  cleaning.value = true
  
  // 确保请求格式符合后端CleanModel
  let requestData = {}
  
  // 根据清洗模式确定ID列表
  if (cleanMode.value === 'selected' && selectedRows.value.length > 0) {
    requestData = { ids: selectedRows.value.map(row => row.id) }
  }
  
  // 显示加载中
  const loadingInstance = ElLoading.service({
    lock: true,
    text: '正在清洗数据，请稍候...',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  
  console.log('发送清洗请求数据:', JSON.stringify(requestData))
  
  // 发送清洗请求
  axios.post('/api/sku/clean', requestData)
    .then(res => {
      ElMessage.success(res.data.message)
      cleanDialogVisible.value = false
      fetchList()
    })
    .catch(error => {
      ElMessage.error(`数据清洗失败: ${error.response?.data?.detail || error.message}`)
      console.error('清洗错误详情:', error.response?.data || error)
    })
    .finally(() => {
      cleaning.value = false
      loadingInstance.close()
    })
}

function openEditCell(row, field) {
  editingCell.value = { rowId: row.id, field }
  // 只拷贝当前字段到 editCache
  editCache.value = { ...row }
}

function handleSaveCell(row, field) {
  // 只保存当前字段，但必须带上 item_name 和 sku
  const value = editCache.value[field]
  axios.post('/api/sku/update', {
    id: row.id,
    item_name: row.item_name,
    sku: row.sku,
    [field]: value,
    human_tag: true  // 添加自动标记
  }).then(() => {
    ElMessage.success('保存成功')
    editingCell.value = { rowId: null, field: '' }
    row.human_tag = true  // 更新本地状态
    fetchList()
  }).catch(error => {
    ElMessage.error(`保存失败: ${error.response?.data?.detail || error.message}`)
  })
}

// 打开AI清洗对话框
function handleAIClean() {
  aiCleanMode.value = selectedRows.value.length > 0 ? 'selected' : 'all'
  aiCleanDialogVisible.value = true
}

// 确认AI清洗
function confirmAIClean() {
  aiCleaning.value = true
  
  // 构建请求数据
  let requestData = {
    skip_handled: skipHandled.value
  }
  
  if (aiCleanMode.value === 'selected' && selectedRows.value.length > 0) {
    requestData.ids = selectedRows.value.map(row => row.id)
  }
  
  // 显示加载中
  const loadingInstance = ElLoading.service({
    lock: true,
    text: 'AI清洗任务启动中...',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  
  // 发送AI清洗请求
  axios.post('/api/sku/ai-clean', requestData)
    .then(res => {
      if (res.data.success) {
        aiCleanTaskId.value = res.data.task_id
        aiCleanProgress.value = null  // 重置进度
        ElMessage.success('AI清洗任务已启动')
        startProgressPolling()
      } else {
        ElMessage.error(res.data.message)
        aiCleaning.value = false
      }
    })
    .catch(error => {
      ElMessage.error(`启动AI清洗失败: ${error.response?.data?.detail || error.message}`)
      console.error('AI清洗错误:', error.response?.data || error)
      aiCleaning.value = false
    })
    .finally(() => {
      loadingInstance.close()
    })
}

// 轮询进度
function startProgressPolling() {
  // 清除可能存在的旧定时器
  if (aiCleanTimer.value) {
    clearInterval(aiCleanTimer.value)
  }
  
  // 开始轮询
  aiCleanTimer.value = setInterval(() => {
    if (!aiCleanTaskId.value) {
      clearInterval(aiCleanTimer.value)
      return
    }
    
    // 验证task_id格式
    try {
      // 验证标准UUID格式
      if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(aiCleanTaskId.value)) {
        throw new Error('无效的任务ID格式')
      }
      
      axios.get(`/api/sku/task-progress/${aiCleanTaskId.value}`)  // 使用路径参数
        .then(res => {
          aiCleanProgress.value = res.data
          
          // 更新进度显示
          if (res.data.status === 'completed') {
            ElMessage.success('清洗完成')
            clearInterval(aiCleanTimer.value)
            aiCleanDialogVisible.value = false
            aiCleaning.value = false
            aiCleanTaskId.value = ''
            aiCleanProgress.value = null
            // 等待一小段时间后刷新列表，确保数据库更新完成
            setTimeout(() => {
              fetchList()
            }, 1000)
          } else if (res.data.status === 'error') {
            ElMessage.error(res.data.message)
            clearInterval(aiCleanTimer.value)
            aiCleanDialogVisible.value = false // 确保错误时也关闭弹框
            aiCleaning.value = false
            aiCleanTaskId.value = ''
            aiCleanProgress.value = null
          }else{
            clearInterval(aiCleanTimer.value)
            aiCleanDialogVisible.value = false
            aiCleaning.value = false
            aiCleanTaskId.value = ''
            aiCleanProgress.value = null
          }
        })
        .catch(error => {
          console.error('获取进度失败:', error)
          clearInterval(aiCleanTimer.value)
          aiCleaning.value = false
          aiCleanTaskId.value = ''
          aiCleanProgress.value = null
          ElMessage.error(`获取进度失败: ${error.response?.data?.detail || error.message}`)
        })
    } catch (error) {
      console.error('无效的任务ID:', error)
      clearInterval(aiCleanTimer.value)
      aiCleaning.value = false
      aiCleanTaskId.value = ''
      aiCleanProgress.value = null
      ElMessage.error('无效的任务ID格式')
    }
  }, 2000)  // 每2秒轮询一次
}

// 处理更新基础数量
async function handleUpdateBaseNum() {
  try {
    const { data } = await ElMessageBox.confirm(
      '此操作将根据商品规格自动更新基础数量，是否继续？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    updateBaseNumLoading.value = true
    const loadingInstance = ElLoading.service({
      lock: true,
      text: '正在更新基础数量...',
      background: 'rgba(0, 0, 0, 0.7)'
    })

    // 调用后端API开始更新
    const response = await axios.post('/api/sku/update-base-num')
    if (response.data.task_id) {
      // 如果返回task_id，说明是异步任务，开始轮询进度
      startUpdateBaseNumProgressPolling(response.data.task_id)
    } else {
      // 同步完成
      ElMessage.success(response.data.message || '更新完成')
      fetchList()
      updateBaseNumLoading.value = false
      loadingInstance.close()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(`更新失败: ${error.response?.data?.detail || error.message}`)
      updateBaseNumLoading.value = false
    }
  }
}

// 轮询更新进度
function startUpdateBaseNumProgressPolling(taskId) {
  // 清除可能存在的旧定时器
  if (updateBaseNumTimer.value) {
    clearInterval(updateBaseNumTimer.value)
  }
  
  // 开始轮询
  updateBaseNumTimer.value = setInterval(async () => {
    try {
      const response = await axios.get(`/api/sku/task-progress/${taskId}`)
      updateBaseNumProgress.value = response.data
      
      // 更新进度显示
      if (response.data.status === 'completed') {
        ElMessage.success(response.data.message)
        clearInterval(updateBaseNumTimer.value)
        updateBaseNumLoading.value = false
        updateBaseNumProgress.value = null
        // 等待一小段时间后刷新列表
        setTimeout(() => {
          fetchList()
        }, 1000)
      } else if (response.data.status === 'error') {
        ElMessage.error(response.data.message)
        clearInterval(updateBaseNumTimer.value)
        updateBaseNumLoading.value = false
        updateBaseNumProgress.value = null
      }
    } catch (error) {
      console.error('获取进度失败:', error)
      clearInterval(updateBaseNumTimer.value)
      updateBaseNumLoading.value = false
      updateBaseNumProgress.value = null
      ElMessage.error(`获取进度失败: ${error.response?.data?.detail || error.message}`)
    }
  }, 2000)  // 每2秒轮询一次
}

// 切换处理状态
async function toggleHandleStatus(row) {
  try {
    await axios.post('/api/sku/update', {
      id: row.id,
      item_name: row.item_name,
      sku: row.sku,
      human_tag: !row.human_tag
    })
    row.human_tag = !row.human_tag
    ElMessage.success('更新成功')
  } catch (error) {
    ElMessage.error(`更新失败: ${error.response?.data?.detail || error.message}`)
  }
}

// 设置筛选状态
function setHandledFilter(filterValue) {
  handledFilter.value = filterValue
  page.value = 1  // 重置到第一页
  fetchList()
}

// 在组件卸载时清理定时器
onUnmounted(() => {
  if (aiCleanTimer.value) {
    clearInterval(aiCleanTimer.value)
  }
  if (updateBaseNumTimer.value) {
    clearInterval(updateBaseNumTimer.value)
  }
})

onMounted(fetchList)
</script>

<style scoped>
.shop-list {
  padding: 20px;
}
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.search-form {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}
.pagination-container {
  margin-top: 20px;
  text-align: right;
}

/* 自定义图片预览样式 */
:deep(.el-image-viewer__wrapper) {
  .el-image-viewer__img {
    max-width: 80%;
    max-height: 80%;
    object-fit: contain;
  }
}

/* 图片加载失败时的样式 */
.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
}

/* 标记图标样式 */
:deep(.el-icon) {
  color: var(--el-border-color);
  transition: all 0.3s;
}

:deep(.el-icon.human_tag) {
  color: var(--el-color-primary);
}

:deep(.el-icon:hover) {
  transform: scale(1.1);
}
</style>
